package com.ey12.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.ey12.utils.DateUtil;

public class AdMgt extends HttpServlet {

	private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
	private static String URL = "";
	private static String USN = "";
	private static String PWD = "";

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */

	private int maxPostSize = 100 * 1024 * 1024;

	public AdMgt() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		URL = this.getServletContext().getInitParameter("DbUrl");
		USN = this.getServletContext().getInitParameter("DbUsername");
		PWD = this.getServletContext().getInitParameter("DbPwd");
		String num = request.getParameter("num");
		
		request.setCharacterEncoding("UTF-8");
		
		System.out.println(num+"********************Access*********************");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String uploadDirectory = this.getServletContext().getInitParameter(
				"AdDirectory");
		
		ArrayList<String> allowedFormats = new ArrayList<String>();
		allowedFormats.add("jpg");
		allowedFormats.add("gif");

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(8192);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxPostSize);
		try {
			List fileItems = upload.parseRequest(request);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String name = item.getName();
					System.out.println(name);
					String[] names = name.split("\\.");
					if (allowedFormats.contains(names[1])) {
						try {
							File file = new File(uploadDirectory + name);
							if(file.exists()){
								file.delete();
							}
							item.write(file);						
							String sql="update gm_config set image_path='"+uploadDirectory + name+"',image_name='"+name+"' where ad_type="+num;
							update(sql);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		
		}
	}

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}



	public static Connection getConnectionByJDBC() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(URL, USN, PWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}



	public void update(String sql) {
		Connection conn = getConnectionByJDBC();
		try {
			Statement stmt = conn.createStatement();
			stmt.execute(sql);
			stmt.close();
			conn.close();
			System.out.println("updateAD="+sql);
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
	}

}
